<template>
  <div class="typewriter-container">
    <div v-if="showResult" class="typewriter-result">
      <div v-for="(section, sIndex) in parsedResult" :key="'section-'+sIndex" class="typewriter-section">
        <h4 v-if="section.title" :class="{'typing': isTyping && currentSection === sIndex && currentElement === 'title'}">
          {{ displayedText[sIndex]?.title || '' }}
          <span v-if="isTyping && currentSection === sIndex && currentElement === 'title'" class="typing-cursor">|</span>
        </h4>
        <div v-for="(paragraph, pIndex) in section.paragraphs" :key="'paragraph-'+sIndex+'-'+pIndex">
          <p :class="{'typing': isTyping && currentSection === sIndex && currentElement === 'p'+pIndex}">
            <span v-html="formatText(displayedText[sIndex]?.[pIndex] || '')"></span>
            <span v-if="isTyping && currentSection === sIndex && currentElement === 'p'+pIndex" class="typing-cursor">|</span>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineProps } from 'vue';

// 接收父组件传递的属性
const props = defineProps({
  parsedResult: {
    type: Array,
    required: true
  },
  displayedText: {
    type: Object,
    required: true
  },
  currentSection: {
    type: Number,
    required: true
  },
  currentElement: {
    type: String,
    required: true
  },
  isTyping: {
    type: Boolean,
    required: true
  },
  showResult: {
    type: Boolean,
    required: true
  }
});

// 格式化文本，将 \n 转换为 <br> 标签
const formatText = (text) => {
  if (!text) return '';
  // 将所有的 \n 替换为 <br> 标签
  return text.replace(/\n/g, '<br>');
};
</script>

<style lang="less" scoped>
.typewriter-container {
  width: 100%;
}

.typewriter-result {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.typewriter-section {
  margin-bottom: 20px;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  h4 {
    font-size: 18px;
    color: #333;
    margin-bottom: 10px;
    font-weight: 600;
  }
  
  p {
    font-size: 16px;
    color: #555;
    line-height: 1.8;
    margin-bottom: 10px;
    white-space: pre-wrap;
    word-wrap: break-word;

    &:last-child {
      margin-bottom: 0;
    }
  }
}

.typing {
  position: relative;
}

.typing-cursor {
  display: inline-block;
  animation: blink 0.7s infinite;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}
</style>
